﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;

namespace RenShiKaoQin.Account
{
    public partial class MeetingRequest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            hrdbEntities ent = new hrdbEntities();
            var result = from emp in ent.TEmployees where emp.FEmployeeID.Equals(Page.User.Identity.Name) select emp;
            TEmployee employee = result.Single();
            TDept dept = employee.TDepts.OrderBy(p => p.FValidDate).Last();
            lbName.Text = employee.FName;
            if (employee.FBirthday.HasValue)
            {
                hfAge.Value = (DateTime.Now.Year - employee.FBirthday.Value.Year).ToString();
            }
            else
            {
                hfAge.Value = "未知";
            }
            var rdept = from tdept in ent.TDictDepts where tdept.FDeptCode.Equals(dept.FKQDeptCode) select tdept;
            try
            {
                lbDept.Text = rdept.Single().FName;
                lbDept.ID = rdept.Single().FDeptCode;
                var rindept = from tindept in ent.TDictDepts where tindept.FDeptCode.Equals(dept.FDeptCode) select tindept;
                lbInDept.Text = rindept.SingleOrDefault().FName;
            }
            catch
            {
                Response.Write("您还没有所属科室或者考勤科室，请联系人事处");
                Response.End();
            }
            lbGender.Text = employee.TDictGender != null ? employee.TDictGender.FName : "未知";
            if (employee.THeadShips.Any())
            {
                THeadShip headShip = employee.THeadShips.OrderBy(p => p.FValidDate).Last();
                lbHeadShip.Text = headShip.TDictHeadShip.FName;
            }
            else
            {
                lbHeadShip.Text = "无";
            }

            if (employee.TTitles.Any())
            {
                TTitle title = employee.TTitles.OrderBy(p => p.FValidDate).Last();
                lbZhiChen.Text = title.TDictTitle.FName;
            }
            else
            {
                lbZhiChen.Text = "无";
            }

            if (employee.TEngageJobs.Any())
            {
                TEngageJob job = employee.TEngageJobs.OrderBy(p => p.FValidDate).Last();
                lbGangWei.Text = job.TDictTitle.FName;
            }
            else
            {
                lbGangWei.Text = "无";
            }
            lbTel.Text = employee.FMobileTel;

            lbBirthday.Text = employee.FBirthday.HasValue ? String.Format("{0:D}", employee.FBirthday.Value) : "";

            ent.Dispose();
            sqlRestRecord.SelectParameters.Clear();
            sqlRestRecord.SelectParameters.Add("FEmployeeID", Page.User.Identity.Name);

            tbStart.Attributes["readonly"] = "readonly";
            tbEnd.Attributes["readonly"] = "readonly";
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            if (tbStart.Text == "" || tbEnd.Text == "") return;
            using (hrdbEntities ent = new hrdbEntities())
            {
                DateTime st = Convert.ToDateTime(tbStart.Text);
                DateTime end = Convert.ToDateTime(tbEnd.Text);
                var result = from rec in ent.TKQRequestRecords where rec.StartDate.Equals(st) && rec.EndDate.Equals(end) && rec.FEmployeeID.Equals(User.Identity.Name) select rec;
                if (result.Any())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Cannotrepeat", "alert('您不能提交重复时间段的申请，如您想修改申请，请先撤销，然后提交新的');", true);
                    return;
                }
                TKQRequestRecord record = TKQRequestRecord.CreateTKQRequestRecord(Page.User.Identity.Name, Convert.ToDateTime(tbStart.Text), Convert.ToDateTime(tbEnd.Text), ddlType.SelectedItem.Value, false, false, 0, false, lbDept.ID, false);
                record.Memo = tbMemo.Text;
                ent.TKQRequestRecords.AddObject(record);
                ent.SaveChanges();
            }
            gvRequest.DataBind();
            ExportByTemplate(ddlType.SelectedItem.Text);
        }
        protected void ExportByTemplate(string type)
        {
            string physicalRoot = HttpContext.Current.Server.MapPath("/QJ");
            string physicalPath = physicalRoot + "/Templates/";
            HSSFWorkbook wb = null;
            string template = null;
            ISheet sheet1 = null;
            if (type == "国内会议")
            {
                template = physicalPath + "国内会议.xls";
                try
                {
                    FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                    wb = new HSSFWorkbook(fs);
                }
                catch (IOException)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "FailtoGenerate", "alert('服务器正忙，请稍后再试');", true);
                    return;
                }
                sheet1 = wb.GetSheet("国内会议");
            }
            else if (type == "国际会议")
            {
                template = physicalPath + "国外会议.xls";
                try
                {
                    FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                    wb = new HSSFWorkbook(fs);
                }
                catch (IOException)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "FailtoGenerate", "alert('服务器正忙，请稍后再试');", true);
                    return;
                }
                sheet1 = wb.GetSheet("境外会议");
            }
            else if (type == "外出进修")
            {
                template = physicalPath + "外出进修.xls";
                try
                {
                    FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                    wb = new HSSFWorkbook(fs);
                }
                catch (IOException)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "FailtoGenerate", "alert('服务器正忙，请稍后再试');", true);
                    return;
                }
                sheet1 = wb.GetSheet("外出进修");
            }
            else
            {
                template = physicalPath + "继教项目.xls";
                try
                {
                    FileStream fs = new FileStream(template, FileMode.Open, FileAccess.Read);
                    wb = new HSSFWorkbook(fs);
                }
                catch (IOException)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "FailtoGenerate", "alert('服务器正忙，请稍后再试');", true);
                    return;
                }
                sheet1 = wb.GetSheet("继续教育");
            }
            if (type != "外出进修")
            {
                sheet1.GetRow(2).GetCell(1).SetCellValue(lbName.Text);
                sheet1.GetRow(2).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(3).SetCellValue(lbDept.Text);
                sheet1.GetRow(2).GetCell(3).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(6).SetCellValue(lbZhiChen.Text);
                sheet1.GetRow(2).GetCell(6).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(9).SetCellValue(lbHeadShip.Text);
                sheet1.GetRow(2).GetCell(9).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(13).SetCellValue(tbZhuanYe.Text);
                sheet1.GetRow(2).GetCell(13).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(1).SetCellValue(tbMemo.Text);
                sheet1.GetRow(3).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                string t = "从" + String.Format("{0:D}", DateTime.Parse(tbStart.Text)) + "至" + String.Format("{0:D}", DateTime.Parse(tbEnd.Text));
                sheet1.GetRow(3).GetCell(5).SetCellValue(t);
                sheet1.GetRow(3).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(10).SetCellValue(tbLocation.Text);
                sheet1.GetRow(3).GetCell(10).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(13).SetCellValue(tbMeetingFee.Text);
                sheet1.GetRow(3).GetCell(13).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(15).SetCellValue(lbTel.Text);
                sheet1.GetRow(3).GetCell(15).CellStyle.Alignment = HorizontalAlignment.CENTER;
                int i = 0;
                if (type == "国际会议")
                {
                    i = 17;
                }
                else
                {
                    i = 16;
                }
                sheet1.GetRow(i).GetCell(1).SetCellValue(lbName.Text);
                sheet1.GetRow(i).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(3).SetCellValue(lbDept.Text);
                sheet1.GetRow(i).GetCell(3).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(6).SetCellValue(lbZhiChen.Text);
                sheet1.GetRow(i).GetCell(6).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(9).SetCellValue(lbHeadShip.Text);
                sheet1.GetRow(i).GetCell(9).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(13).SetCellValue(tbZhuanYe.Text);
                sheet1.GetRow(i).GetCell(13).CellStyle.Alignment = HorizontalAlignment.CENTER;

                i++;
                sheet1.GetRow(i).GetCell(1).SetCellValue(tbMemo.Text);
                sheet1.GetRow(i).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(5).SetCellValue(t);
                sheet1.GetRow(i).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(10).SetCellValue(tbLocation.Text);
                sheet1.GetRow(i).GetCell(10).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(13).SetCellValue(tbMeetingFee.Text);
                sheet1.GetRow(i).GetCell(13).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(i).GetCell(15).SetCellValue(lbTel.Text);
                sheet1.GetRow(i).GetCell(15).CellStyle.Alignment = HorizontalAlignment.CENTER;
            }
            else if (type == "外出进修")
            {
                sheet1.GetRow(2).GetCell(1).SetCellValue(lbName.Text);
                sheet1.GetRow(2).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(3).SetCellValue(lbGender.Text);
                sheet1.GetRow(2).GetCell(3).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(5).SetCellValue(hfAge.Value);
                sheet1.GetRow(2).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(2).GetCell(7).SetCellValue(lbZhiChen.Text);
                sheet1.GetRow(2).GetCell(7).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(1).SetCellValue(lbDept.Text);
                sheet1.GetRow(3).GetCell(2).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(5).SetCellValue(tbZhuanYe.Text);
                sheet1.GetRow(3).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(3).GetCell(8).SetCellValue(lbTel.Text);
                sheet1.GetRow(3).GetCell(8).CellStyle.Alignment = HorizontalAlignment.CENTER;

                sheet1.GetRow(4).GetCell(1).SetCellValue(tbMemo.Text);
                sheet1.GetRow(4).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(4).GetCell(5).SetCellValue(tbStart.Text + "至" + tbEnd.Text);
                sheet1.GetRow(4).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(4).GetCell(8).SetCellValue(tbLocation.Text);
                sheet1.GetRow(4).GetCell(8).CellStyle.Alignment = HorizontalAlignment.CENTER;
                int j = 17;
                sheet1.GetRow(j).GetCell(1).SetCellValue(lbName.Text);
                sheet1.GetRow(j).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(3).SetCellValue(lbGender.Text);
                sheet1.GetRow(j).GetCell(3).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(5).SetCellValue(hfAge.Value);
                sheet1.GetRow(j).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(7).SetCellValue(lbZhiChen.Text);
                sheet1.GetRow(j).GetCell(7).CellStyle.Alignment = HorizontalAlignment.CENTER;
                j++;
                sheet1.GetRow(j).GetCell(1).SetCellValue(lbDept.Text);
                sheet1.GetRow(j).GetCell(2).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(5).SetCellValue(tbZhuanYe.Text);
                sheet1.GetRow(j).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(8).SetCellValue(lbTel.Text);
                sheet1.GetRow(j).GetCell(8).CellStyle.Alignment = HorizontalAlignment.CENTER;
                j++;
                sheet1.GetRow(j).GetCell(1).SetCellValue(tbMemo.Text);
                sheet1.GetRow(j).GetCell(1).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(5).SetCellValue(tbStart.Text + "至" + tbEnd.Text);
                sheet1.GetRow(j).GetCell(5).CellStyle.Alignment = HorizontalAlignment.CENTER;
                sheet1.GetRow(j).GetCell(8).SetCellValue(tbLocation.Text);
                sheet1.GetRow(j).GetCell(8).CellStyle.Alignment = HorizontalAlignment.CENTER;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                wb.Write(ms);
                byte[] data = ms.ToArray();
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                //Encoding pageEncode = Encoding.GetEncoding(PageEncode);
                response.Charset = "UTF-8";
                response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
                response.AddHeader("Content-Disposition", string.Format("attachment; filename=Meeting.xls"));
                response.BinaryWrite(data);
            }
        }

        protected void gvRequest_RowCommand(object sender, GridViewCommandEventArgs e)
        {

        }

        protected void gvRequest_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int serial = Convert.ToInt32(e.Keys[0]);
            using (hrdbEntities ent = new hrdbEntities())
            {
                var result = from rec in ent.TKQRequestRecords where rec.SerialNO == serial select rec;
                if (result.Any())
                {
                    TKQRequestRecord record = result.Single();
                    if (record.CheckStatus == false && record.ExamStatus == false)
                    {
                        e.Cancel = false;
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "Cannotdelete", "alert('只有未被审批和复核的申请才可以撤销');", true);
                        e.Cancel = true;
                    }
                }
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            gvRequest.DataBind();
        }
    }
}